package net.lesscoding.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @author eleven
 * @date 2024/10/28 15:41
 * @apiNote
 */
@Slf4j
public class ByteBufTest {

    @Test
    public void writeTest() {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(10);
        buffer.writeBoolean(true);
        buffer.writeBoolean(false);
        buffer.writeInt(0250);
        buffer.writeIntLE(0250);
        printBuf(buffer);
    }

    @Test
    public void byteBufTest() {
        // 1. 创建一个ByteBuf
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        printBuf(buffer);
        int capacity = 100;
        StringBuilder stringBuilder = new StringBuilder(capacity);
        for (int i = 0; i < capacity; i++) {
            stringBuilder.append("0" + i);
        }
        buffer.writeBytes(stringBuilder.toString().getBytes());
        printBuf(buffer);
    }

    /**
     * 使用 netty工具类打印 ByteBuf 内容
     * @param byteBuf     ByteBuf
     */
    public static void printBuf(ByteBuf byteBuf) {
        int length = byteBuf.readableBytes();
        int rows = length / 16 + (length % 15 == 0? 0 : 1) + 4;
        StringBuilder sb = new StringBuilder(rows * 80 * 2)
                .append("read index: ").append(byteBuf.readerIndex())
                .append("write index: ").append(byteBuf.writerIndex())
                .append("capacity:").append(byteBuf.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(sb, byteBuf);
        System.out.println(sb);
    }
}
